package com.wss.lsl.test.driven.scoketio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class TimeClientSelector {

	public static void main(String[] args) throws Exception {
		// 客户端如何编程呢
		ByteBuffer bb = ByteBuffer.allocate(1024);

		SocketChannel sc = SocketChannel.open();
		Selector s = Selector.open();
		
		sc.configureBlocking(false);
		sc.register(s, SelectionKey.OP_CONNECT);
		sc.connect(new InetSocketAddress(8888));
		
		while(true) {
			s.select();
			Set<SelectionKey> keys = s.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			while(it.hasNext()) {
				SelectionKey key = it.next();
				if(key.isConnectable()) {
					// 连接完之后开始读
					SocketChannel client = (SocketChannel)key.channel();
					if(client.isConnectionPending()) {
						client.finishConnect();
					}
					client.configureBlocking(false);
					client.register(s, SelectionKey.OP_READ);
				} else if(key.isReadable()) {
					SocketChannel client = (SocketChannel)key.channel();
					client.configureBlocking(false);
					
					int count = client.read(bb);
					bb.flip();
					System.out.println("read:" + new String(bb.array(), 0, count));
					bb.clear();
					
					client.register(s, SelectionKey.OP_WRITE);
				} if(key.isWritable()) {
					System.out.println("isWritable");
					SocketChannel client = (SocketChannel)key.channel();
					client.configureBlocking(false);
					
					bb.put("123".getBytes());
					bb.flip();
					client.write(bb);
					bb.clear();
					
					TimeUnit.SECONDS.sleep(1);
					
					client.register(s, SelectionKey.OP_READ);
				}
			}
			keys.clear();
		}
	}
}
